package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.dialog.CommonDialog
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent
import com.kanshu.ksgb.fastread.doudou.common.business.event.LoginEvent
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ActivateService
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindInfo
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UpdateInfoEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.ss.android.common.lib.AppLogNewUtils
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_account_management.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject

/**
 * Created by xubo on 2018/11/21
 */
@Route(path = ARouterConfig.PERSONAL_ACCOUNT_MANAGE)
class AccountManagementActivity : BaseActivity(), View.OnClickListener {

    var mPhone = ""
    private var infoLoaded = false
    private var alipayInfo: BindInfo? = null
    private var wechatInfo: BindInfo? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_account_management)
        setTitle("账号管理")
        update_phone.setOnClickListener(this)
        apply_bind_account.setOnClickListener(this)
        wechat_bind_account.setOnClickListener(this)
        update_login_user.setOnClickListener(this)
        exit_login.setOnClickListener(this)
        mPhone = StorageUtils.getPreference(this@AccountManagementActivity, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), "")
        bind_phone.text = Utils.securityShowPhone(mPhone)
        loadBindInfo()
        EventBus.getDefault().register(this)
    }


    @SuppressLint("ApplySharedPref")
    override fun onClick(v: View?) {
        if (v == null) {
            return
        }
        when (v.id) {
            R.id.update_phone -> {
//                val Intent = Intent(this, SecurityCheckActivity::class.java)
//                Intent.putExtra("phone", mPhone)
//                startActivityForResult(Intent, 100)
                var map = HashMap<String, String>()
                map.put("phone", mPhone)
                ARouterUtils.toActivityForResult(this@AccountManagementActivity, ARouterConfig.PERSONAL_SECURITY_CHECK, map, 100)
            }
            R.id.apply_bind_account -> {
                if (!infoLoaded) {
                    ToastUtil.showMessage("信息加载中，请稍后再试")
                    return
                }
                if (alipayInfo == null) {
                    BindAccountActivity.actionStart(this)
                }
            }
            R.id.wechat_bind_account -> {
                if (!infoLoaded) {
                    ToastUtil.showMessage("信息加载中，请稍后再试")
                    return
                }
                if (wechatInfo == null) {
                    BindAccountActivity.actionStart(this)
                }
            }
            R.id.update_login_user -> {
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "")
            }
            R.id.exit_login -> {
                CommonDialog.show(this@AccountManagementActivity, "确定要退出登录吗", object : CustomDialog.Callback {
                    override fun onSure(dialog: Dialog) {
                        exitLogin()
                        dialog.dismiss()
                    }

                    override fun onCancel(dialog: Dialog) {
                        dialog.dismiss()
                    }
                }).setSureText("退出")
            }
        }
    }

    private fun exitLogin() {
        //头条上报游客模式事件
        AdPresenter.touTiaoEvent(R.string.tourists_mode_event,getString(R.string.TOU_TIAO_USER_ID),UserUtils.getUserId())
        //DownloadBookService.clearAll()
        ARouter.getInstance().navigation(ActivateService::class.java).clearQueue()
        MMKVUserManager.getInstance().loginState = Constants.LoginState.TYPE_NO_LOGIN
        UserUtils.saveUserId(MMKVDefaultManager.getInstance().deviceUserId)
        val event = LoginEvent()
        EventBus.getDefault().post(event)
        finish()
    }

    /**
     * 获取最新的绑定账号
     */
    private fun loadBindInfo() {
        val retrofitHelper = RetrofitHelper.getInstance()
        retrofitHelper.createService(PersonCenterService::class.java)
                .getAccountBindInfo()
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<List<BindInfo>>> {
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t: BaseResult<List<BindInfo>>?) {
                        infoLoaded = true
                        val size = t?.result?.data?.size ?: 0
                        if (size != 0) {
                            t?.result?.data?.forEach {
                                when (it.type) {
                                    BindInfo.TYPE_ALIPAY -> {
                                        alipayInfo = it
                                        updateAlipayView(it.nickname)
                                    }
                                    BindInfo.TYPE_WECHAT -> {
                                        wechatInfo = it
                                        updateWechatView(it.nickname)
                                    }
                                    else -> Log.i("test", "code error ${it.type}")
                                }

                            }

                        } else {
                            updateAlipayView(null)
                            updateWechatView(null)
                        }

                    }

                    override fun onError(e: Throwable?) {
                        infoLoaded = true
                        dismissLoading()
                        e?.printStackTrace()
                    }
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    fun handleBindEvent(event: BindInfo) {
        if (!event.result) {
            ToastUtil.showMessage("绑定失败")
            return
        }
        when (event.type) {
            BindInfo.TYPE_ALIPAY -> {
                loadBindInfo()
            }
            BindInfo.TYPE_WECHAT -> updateWechatView(event.nickname)
            else -> Log.i("test", "code error ${event.type}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEditInfo(event: UpdateInfoEvent) {
        loadBindInfo()
    }

    private fun updateAlipayView(name: String?) {
        bind_alipay_name.text = name
        if (!TextUtils.isEmpty(name)) {
            alipay_bind_state.setImageResource(R.mipmap.ic_has_bind)
        } else {
            alipayInfo = null
            alipay_bind_state.setImageResource(R.mipmap.ic_add_bind)
        }
    }


    private fun updateWechatView(name: String?) {
        bind_wechat_name.text = name
        if (!TextUtils.isEmpty(name)) {
            wechat_bind_state.setImageResource(R.mipmap.ic_has_bind)
        } else {
            wechatInfo = null
            wechat_bind_state.setImageResource(R.mipmap.ic_add_bind)
        }
    }

    companion object {
        fun actionStart(activity: Activity) {
            val intent = Intent(activity, AccountManagementActivity::class.java)
            activity.startActivity(intent)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleLoginEvent(event: LoginEvent) {
        if (MMKVUserManager.getInstance().loginState == Constants.LoginState.TYPE_HAS_LOGIN) {
            finish()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleBindEvent(bindEvent: BindEvent) {
        if (bindEvent.code == BindEvent.SUCCESS) {
            mPhone = StorageUtils.getPreference(this@AccountManagementActivity, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), "")
            bind_phone.text = Utils.securityShowPhone(mPhone)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}